package first_practice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-54-螺旋矩阵
 * @date 2025/3/30 16:44
 */
public class Solution54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();
        int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
        while (top <= bottom && left <= right) {

            for (int i = left; i < right; i++) {
                ans.add(matrix[top][i]);
            }

            for (int i = top; i < bottom; i++) {
                ans.add(matrix[i][right]);
            }

            if (top != bottom) { // 剩余1行以上
                for (int i = right; i > left; i--) {
                    ans.add(matrix[bottom][i]);
                }
            } else {
                ans.add(matrix[top][right]);
                break;
            }

            if (left != right) { // 剩余1列以上
                for (int i = bottom; i > top; i--) {
                    ans.add(matrix[i][left]);
                }
            } else {
                ans.add(matrix[bottom][right]);
                break;
            }

            top++;
            bottom--;
            left++;
            right--;
        }
        return ans;
    }
}
